package leetcode.editor.cn.q1_300.q;

/**
 * @author qidi
 * @date 2021-11-02 09:49:22
 */
class Q0023_MergeKSortedLists {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if (lists.length == 0) return null;
            return process(lists, 0, lists.length - 1);
        }

        private ListNode process(ListNode[] lists, int l, int r) {
            if (l == r) return lists[l];

            int mid = l + ((r - l) >> 2);
            ListNode ll = process(lists, l, mid);
            ListNode rl = process(lists, mid + 1, r);
            return merge(ll, rl);
        }

        private ListNode merge(ListNode l1, ListNode l2) {
            if (l1 == null) return l2;
            if (l2 == null) return l1;

            ListNode head = null;
            ListNode cur = null;
            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    if (head == null) {
                        head = new ListNode(l1.val);
                        cur = head;
                    } else {
                        cur.next = new ListNode(l1.val);
                        cur = cur.next;
                    }
                    l1 = l1.next;
                } else {
                    if (head == null) {
                        head = new ListNode(l2.val);
                        cur = head;
                    } else {
                        cur.next = new ListNode(l2.val);
                        cur = cur.next;
                    }
                    l2 = l2.next;
                }
            }

            while (l1 != null) {
                cur.next = new ListNode(l1.val);
                l1 = l1.next;
                cur = cur.next;
            }
            while (l2 != null) {
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
                cur = cur.next;
            }

            return head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0023_MergeKSortedLists().new Solution();
    }
}